<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.jsdelivr.net/npm/webrtc-adapter@7.6.1/out/adapter.js"></script>
</head>
<body>
cameras: <br>
<ul></ul>
<br>
<video autoplay muted playsinline></video>
<h3>Capabilities:</h3>
<pre id="capabilities"></pre>

<script>
const listEl = document.querySelector("ul")

const renderOptions = (currentDeviceId, devices) => {
  listEl.innerHTML = ""

  devices
    .filter(deviceInfo => deviceInfo.kind === "videoinput")
    .map(({ label, deviceId }) => {
      const el = document.createElement('li')

      if (deviceId == currentDeviceId) {
        el.innerHTML = `<a href="#" onclick="selectCamera('${deviceId}')">${label}</a>`
      } else {
        el.innerHTML = `<a href="#" onclick="selectCamera('${deviceId}')">${label}</a>`
      }

      return el
    })
    .forEach(el => listEl.appendChild(el))
}


let stream

const selectCamera = async deviceId => {
  try {
    console.log(deviceId)

    if (stream) {
      stream.getTracks().forEach(track => track.stop())
    }

    const videoConstraints = {};
    if (!deviceId) {
       videoConstraints.facingMode = 'environment';
    } else {
       videoConstraints.deviceId = { exact: deviceId };
    }

    stream = await navigator.mediaDevices.getUserMedia({
      audio: false,
      video: videoConstraints,
    })

    const videoEl = document.querySelector('video')
    videoEl.srcObject = stream

    const [ videoTrack ] = stream.getVideoTracks()

    renderOptions(
      videoTrack.getSettings().deviceId,
      await navigator.mediaDevices.enumerateDevices()
    )

    const capEl = document.querySelector("#capabilities")
    capEl.innerText = JSON.stringify(videoTrack.getCapabilities(), null, 2)
  } catch (error) {
    console.error(error)
  }
}

selectCamera()
</script>
</body>
</html>
